/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package no.ffi.tpm;

import java.io.Serializable;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import no.ffi.tpm.crypto.CryptoOperations;
import no.ffi.tpm.crypto.SignedObject;



/**
 *
 * @author anders
 */
public class TPMiSRequest extends SignedObject implements Serializable {
    private LegacyKeyCertifyInfo tpmSignedPart;
    private final String SubjectId;
    private String AIKsnr;
    private final byte[] PCRHash;
   
    
    public TPMiSRequest(LegacyKeyCertifyInfo lkCertInfo,byte[] sign,byte[] PCRs){
        super(CryptoOperations.serialize(lkCertInfo),sign);
        this.PCRHash=PCRs;
        this.SubjectId=lkCertInfo.getSubjId();
        this.tpmSignedPart=lkCertInfo;
        this.AIKsnr=tpmSignedPart.getAikSNR();
    }
      
    public boolean verifyRequest(PublicKey aik,PublicKey userKey, byte[] nonce) { 
    boolean valid=true;
    //Calculate the key digest separately based on the modulus sent in the CertificateRequest
        byte[] calculatedDig = CryptoOperations.pubKeytoSHA1(tpmSignedPart.getCertifiedKey());

        //Check that the public key digests match
        if (Arrays.equals(tpmSignedPart.getCertifiedKeySHA1(), calculatedDig)) {
            //Then the nonces match
            if (Arrays.equals(tpmSignedPart.getNonce(),nonce)) {
                try {
                     
                    valid = valid && CryptoOperations.verify(tpmSignedPart, aik);//sig.verify(sign);
                    if (valid) {
                        System.out.println("The key is valid, here is your Identity statement....");
                    }
                } catch (Exception ex) {
                    Logger.getLogger(TPMiSRequest.class.getName()).log(Level.SEVERE, null, ex);
                } 
            } else {
                System.out.println("Nonces are not equal");
            }
        } else {
            System.out.println("PubKey digests are not equal");
        }
        try {
            valid = valid & CryptoOperations.verify(this, userKey);
        } catch (Exception ex) {
            Logger.getLogger(TPMiSRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
    return valid;
    } 

    /**
     * @return the tpmSignedPart
     */
    public LegacyKeyCertifyInfo getTpmSignedPart() {
        return tpmSignedPart;
    }

    /**
     * @return the SubjectId
     */
    public String getSubjectId() {
        return SubjectId;
    }

    /**
     * @return the AIKsnr
     */
    public String getAIKsnr() {
        return AIKsnr;
    }

    /**
     * @return the PCRHash
     */
    public byte[] getPCRHash() {
        return PCRHash;
    }
    
}
